<template>
  <div class="order">
    <div class="top">
      <van-nav-bar
        title="订单结算"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
    </div>
    <div class="address-box">
      <div class="address">
        <div class="select">
          <span @click="selectAddress">选择收货地址</span>
          <van-icon name="arrow" class="icon" />
        </div>
        <div class="user-info">
          <span class="name">{{ initAddress.name }}</span>
          <span class="phone">{{ initAddress.tel }}</span>
          <i class="ico" v-show="initAddress.isDefault">默认</i>
        </div>
        <div class="address-info">
          <span>{{ initAddress.address }}</span>
        </div>
      </div>
    </div>
    <div class="order-box">
      <div class="order-info">
        <span>订单信息</span>
        <Orderitem v-for="(v, i) in orderArr" :key="i" :product="v"></Orderitem>
        <div class="bottom">
          <div v-show="status">{{ time }}</div>
          <div class="info">
            <div class="num">共计 {{ num }} 件</div>
            <div class="sum">合计 ￥{{ sum }}</div>
          </div>
        </div>
      </div>
    </div>

    <van-popup v-model="isOpenShow" position="bottom" closeable>
      <van-address-list
        :list="addList"
        default-tag-text="默认"
        @add="onAdd"
        :switchable="false"
        @click-item="taggetAddress"
      />
    </van-popup>

    <div class="btn" @click="settlement">立即结算</div>
  </div>
</template>

<script>
import "../assets/less/order.less";
import Orderitem from "../components/Orderitem.vue";
import { mapState, mapMutations } from "vuex";
export default {
  name: "Order",
  components: {
    Orderitem,
  },
  computed: {
    ...mapState(["shopBag"]),
  },
  computed: {
    num() {
      let count = 0;
      for (let i = 0; i < this.orderArr.length; i++) {
        count += this.orderArr[i].count;
      }
      return count;
    },
    sum() {
      let total = 0;
      for (let i = 0; i < this.orderArr.length; i++) {
        total += this.orderArr[i].count * this.orderArr[i].price;
      }
      return total;
    },
  },
  data() {
    return {
      // 是否显示默认地址
      isDefault: true,

      // 选择地址
      isOpenShow: false,
      // 地址详情
      addList: [],
      // 订单商品id
      sids: "",
      // 订单商品数组
      orderArr: [],
      // 地址数据
      initAddress: {},
    };
  },

  created() {
    this.inquireAdd();
    console.log(11);
    this.sids = this.$route.query.sids.split("-");
    // console.log("sids ==> ", this.sids);
    // 查询订单商品
    this.inquireOrder();
  },
  methods: {
    ...mapMutations(["changeShopBag", "changeIsShopBag"]),
    // 返回
    onClickLeft() {
      this.$router.go(-1);
    },

    // 选择地址
    selectAddress() {
      this.isOpenShow = true;
    },
    // 查询地址
    inquireAdd() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "get",
        url: this.baseUrl + "/findAddress",
        params: {
          appkey: this.appkey,
          tokenString: tokenString,
        },
      })
        .then((result) => {
          console.log(result);
          this.$toast.clear();
          if (result.data.code == 700) {
            return this.$router.push({ name: "Login" });
          }
          if (result.data.code === 20000) {
            result.data.result.forEach((v) => {
              v.address = `${v.province}${v.city}${v.county}${v.addressDetail}`;
              v.isDefault = !!v.isDefault;
              this.addList.push(v);
            });
            this.addList.forEach((item) => {
              if (item.isDefault) { //有默认就显示默认
                this.initAddress = item;
              }else{ //没有默认地址就显示地址数组中的第一条
                this.initAddress = this.addList[0];
              }
            });
            console.log(this.initAddress);
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },
    // 新增地址
    onAdd() {
      this.$router.push({ name: "Address" });
    },

    // 查询订单页面
    inquireOrder() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        return;
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "get",
        url: this.baseUrl + "/commitShopcart",
        params: {
          appkey: this.appkey,
          tokenString: tokenString,
          sids: JSON.stringify(this.sids),
        },
      })
        .then((result) => {
          console.log(result);
          this.$toast.clear();
          if (result.data.code == 700) {
            return;
          }
          if (result.data.code === 50000) {
            if (result.data.result.length == 0) {
              this.changeIsShopBag(false);
              return this.$router.push({ path: "/" });
            }
            this.orderArr = result.data.result;
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 切换地址
    taggetAddress(item, index) {
      this.initAddress = item;
      this.isOpenShow = false;
    },

    // 结算订单
    settlement() {
      if (!this.initAddress.address || !this.initAddress.name) {
        this.$toast.loading({
          message: "请选择地址",
          forbidClick: true,
          duration: 1000,
        });
        return;
      }
      let tokenString = this.$cookies.get("tokenString");
      //当用户未登录的时候跳转到登录页面
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "post",
        url: this.baseUrl + "/pay",
        data: {
          appkey: this.appkey,
          tokenString: tokenString,
          sids: JSON.stringify(this.sids),
          phone: this.initAddress.tel,
          address: this.initAddress.address,
          receiver: this.initAddress.name,
        },
      })
        .then((result) => {
          console.log(result);
          this.$toast.clear();
          if (result.data.code === 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          } else if (result.data.code === 60000) {
            // 修改购物袋数量
            this.changeShopBag(this.shopBag - this.sids.length);

            return this.$router.push({ name: "Myorder" });
          }
          this.$toast({
            message: result.data.msg,
            forbidClick: true,
            duration: 3000,
          });
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },
  },
};
</script>
